package com.mine.modules.vm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.mine.common.config.exception.MineBootException;
import com.mine.common.domain.dto.LoginModel;
import com.mine.common.domain.vo.Result;
import com.mine.common.utils.AnnotationUtil;
import com.mine.common.utils.ToTreeUtil;
import com.mine.common.utils.oConvertUtils;
import com.mine.modules.sys.domain.dto.RoleDto;
import com.mine.modules.sys.entity.SysDictItem;
import com.mine.modules.sys.service.ISysDictItemService;
import com.mine.modules.sys.service.ISysUserRoleService;
import com.mine.modules.vm.common.constant.BizConstant;
import com.mine.modules.vm.domain.dto.*;
import com.mine.modules.vm.domain.query.CountElementQuery;
import com.mine.modules.vm.domain.query.LayerQuery;
import com.mine.modules.vm.entity.*;
import com.mine.modules.vm.mapper.VmLayerMapper;
import com.mine.modules.vm.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.soap.Node;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 场景菜单 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-10-15
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class VmLayerServiceImpl extends ServiceImpl<VmLayerMapper, VmLayer> implements IVmLayerService {

    private final ISysUserRoleService sysUserRoleService;

    private final IVmRoleLayerService vmRoleLayerService;

    private final IVmPermissionLayerService vmPermissionLayerService;

    private final IVmCommonService vmCommonService;

    private final ISysDictItemService sysDictItemService;

    private final IVmLayerElementService vmLayerElementService;

    private final IVmLayerActionService vmLayerActionService;

    @Override
    public Result<?> listAll(LayerQuery layerQuery) {
        long start = System.currentTimeMillis();
        try {
            LambdaQueryWrapper<VmLayer> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.and(StringUtils.isNotBlank(layerQuery.getKeywords()), e -> e
                    .like(VmLayer::getLayerName, layerQuery.getKeywords())
                    .or()
                    .like(VmLayer::getLayerCode, layerQuery.getKeywords())
            );
//            queryWrapper.eq(StringUtils.isNotBlank(layerQuery.getParentId()), VmLayer::getParentId, layerQuery.getParentId());
            if (StringUtils.isNotBlank(layerQuery.getMenuId())) {
                List<String> layerIds = vmPermissionLayerService.lambdaQuery().list().stream().map(VmPermissionLayer::getLayerId).collect(Collectors.toList());
                if (layerIds.isEmpty()) {
                    return Result.OK("查询成功！", Collections.emptyList());
                }
                queryWrapper.in(VmLayer::getId, layerIds);
            }
            queryWrapper.orderByAsc(VmLayer::getSort);
            List<VmLayer> list = Collections.emptyList();

            if (StringUtils.isNotBlank(layerQuery.getParentId())) {
                list = new ArrayList<>();
                getAllIdByParentId(list, layerQuery.getParentId());
            } else {
                list = this.list(queryWrapper);
            }
            List<VmLayer> treeList = new ArrayList<>();
            if (StringUtils.isNotEmpty(layerQuery.getKeywords())) {
                if (list != null && !list.isEmpty()) {
                    treeList = list;
                }
            } else {
                ToTreeUtil.getTreeList(treeList, list, null, layerQuery.getParentId());
            }
            log.info("======获取全部场景菜单数据=====耗时:{}毫秒", System.currentTimeMillis() - start);
            return Result.OK("查询成功！", treeList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    @Override
    public Result<?> listByParentId(LayerQuery layerQuery) {
        LambdaQueryWrapper<VmLayer> queryWrapper = new LambdaQueryWrapper<>(VmLayer.class);
        if (layerQuery != null) {
            if (StringUtils.isNotBlank(layerQuery.getParentId())) {
                queryWrapper.eq(VmLayer::getParentId, layerQuery.getParentId());
            } else {
                queryWrapper.isNull(VmLayer::getParentId).or().eq(VmLayer::getParentId, "");
            }
            if (StringUtils.isNotBlank(layerQuery.getKeywords())) {
                queryWrapper.and(e -> e
                        .like(VmLayer::getLayerName, layerQuery.getKeywords())
                        .or()
                        .like(VmLayer::getLayerCode, layerQuery.getKeywords())
                );
            }
        } else {
            queryWrapper.isNull(VmLayer::getParentId).or().eq(VmLayer::getParentId, "");
        }
        queryWrapper.orderByAsc(VmLayer::getSort);
        return Result.ok(this.list(queryWrapper));
    }

    @Override
    public Result<?> getMenuLayerByToken(LayerQuery layerQuery) {
        long start = System.currentTimeMillis();
        try {
            //直接获取当前用户不适用前端token
            LoginModel loginUser = (LoginModel) SecurityUtils.getSubject().getPrincipal();
            if (oConvertUtils.isEmpty(loginUser)) {
                return Result.error("请登录系统！");
            }
            LambdaQueryWrapper<VmLayer> queryWrapper = new LambdaQueryWrapper<>();
            //权限过滤
            List<String> roleLayerIds = Collections.emptyList();
            List<String> menuLayerIds = Collections.emptyList();
            menuLayerIds = vmPermissionLayerService.getLayerIdsByMenuId(layerQuery.getMenuId());
            if (menuLayerIds.isEmpty()) {
                return Result.error("菜单未绑定图层！");
            }
            queryWrapper.in(VmLayer::getId, menuLayerIds);
            if (!StringUtils.equals("admin", loginUser.getUsername())) {
                roleLayerIds = vmRoleLayerService.getLayerIdsIdsByRoleIds(
                        sysUserRoleService.getRoleIdsByUerId(loginUser.getId())
                );
                queryWrapper.in(!roleLayerIds.isEmpty(), VmLayer::getId, roleLayerIds);
            }
//            queryWrapper.eq(StringUtils.isNotBlank(layerQuery.getParentId()), VmLayer::getParentId, layerQuery.getParentId());
            queryWrapper.orderByAsc(VmLayer::getSort);
            List<VmLayer> list = Collections.emptyList();

            if (StringUtils.isNotBlank(layerQuery.getParentId())) {
                list = new ArrayList<>();
                getAllIdByParentId(list, layerQuery.getParentId());
            } else {
                list = this.list(queryWrapper);
            }
            List<VmLayer> treeList = new ArrayList<>();
            if (StringUtils.isNotEmpty(layerQuery.getKeywords())) {
                if (list != null && !list.isEmpty()) {
                    treeList = list;
                }
            } else {
                ToTreeUtil.getTreeList(treeList, list, null, layerQuery.getParentId());
            }
            log.info("======获取全部场景菜单数据=====耗时:{}毫秒", System.currentTimeMillis() - start);
            return Result.OK("查询成功！", treeList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    @Override
    public Result<?> getMenuLayerListByToken(LayerQuery layerQuery) {
        try {
            //直接获取当前用户不适用前端token
            LoginModel loginUser = (LoginModel) SecurityUtils.getSubject().getPrincipal();
            if (oConvertUtils.isEmpty(loginUser)) {
                return Result.error("请登录系统！");
            }
            LambdaQueryWrapper<VmLayer> queryWrapper = new LambdaQueryWrapper<>();
            //权限过滤
            List<String> roleLayerIds = Collections.emptyList();
            List<String> menuLayerIds = Collections.emptyList();
            menuLayerIds = vmPermissionLayerService.getLayerIdsByMenuId(layerQuery.getMenuId());
            if (menuLayerIds.isEmpty()) {
                return Result.error("菜单未绑定图层！");
            }
            queryWrapper.in(VmLayer::getId, menuLayerIds);
            if (!StringUtils.equals("admin", loginUser.getUsername())) {
                roleLayerIds = vmRoleLayerService.getLayerIdsIdsByRoleIds(
                        sysUserRoleService.getRoleIdsByUerId(loginUser.getId())
                );
                queryWrapper.in(!roleLayerIds.isEmpty(), VmLayer::getId, roleLayerIds);
            }
            if (StringUtils.isNotBlank(layerQuery.getParentId())) {
                queryWrapper.eq(VmLayer::getParentId, layerQuery.getParentId());
            } else {
                queryWrapper.and(
                        e -> e.isNull(VmLayer::getParentId).or().eq(VmLayer::getParentId, "")
                );
            }
            queryWrapper.orderByAsc(VmLayer::getSort);
            List<VmLayer> list = this.list(queryWrapper);
            return Result.OK("查询成功！", list);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }


    private List<VmLayer> listByParentIds(List<String> parentIds) {
        List<VmLayer> list = new ArrayList<>();
        for (String parentId : parentIds) {
            list.addAll(listByParentId(parentId));
        }
        return list;
    }

    private List<VmLayer> listByParentId(String parentId) {
        List<VmLayer> list = new ArrayList<>();
        List<VmLayer> vmLayers = lambdaQuery().eq(VmLayer::getParentId, parentId).list();
        if (!vmLayers.isEmpty()) {
            list.addAll(vmLayers);
            for (VmLayer vmLayer : vmLayers) {
                list.addAll(this.listByParentId(vmLayer.getId()));
            }
        }
        return list;
    }

    @Override
    public Result<?> addOrEdit(VmLayerDto layerDto) {
        if (layerDto == null) {
            return Result.error("参数必填！");
        }
        if (StringUtils.isEmpty(layerDto.getId())) {
            //新增
            VmLayer vmLayer = BeanUtil.toBean(layerDto, VmLayer.class);
//            vmLayer.setLayerLevel(BizConstant.LAYER_LEVEL_LAYER);
            if (this.save(vmLayer)) {
                return Result.OK("添加成功！");
            } else {
                return Result.error("添加失败！");
            }
        } else {
            VmLayer vmLayer = this.getById(layerDto.getId());
            if (vmLayer == null) {
                return Result.error("数据不存在，请刷新重试！");
            }
            String sceneLayerId = vmLayer.getSceneLayerId();
            vmLayer = BeanUtil.toBean(layerDto, VmLayer.class);
            vmLayer.setSceneLayerId(sceneLayerId);
            if (this.updateById(vmLayer)) {
                return Result.OK("修改成功！");
            } else {
                return Result.error("修改失败！");
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> delete(String id) {
        try {
            this.deleteLayer(id);
            return Result.OK("删除成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> deleteBatch(String ids) {
        try {
            String[] arr = ids.split(",");
            for (String id : arr) {
                if (oConvertUtils.isNotEmpty(id)) {
                    try {
                        this.deleteLayer(id);
                    } catch (MineBootException e) {
                        if (e.getMessage() != null && e.getMessage().contains("未找到图层信息")) {
                            log.warn(e.getMessage());
                        } else {
                            throw e;
                        }
                    }
                }
            }
            return Result.OK("删除成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("删除失败!");
        }
    }

    @Override
    public Result<List<String>> queryRoleLayer(String roleId) {
        Result<List<String>> result = new Result<>();
        try {
            List<VmRoleLayer> list = vmRoleLayerService.list(new QueryWrapper<VmRoleLayer>().lambda().eq(VmRoleLayer::getRoleId, roleId));
            result.setResult(list.stream().map(e -> String.valueOf(e.getLayerId())).collect(Collectors.toList()));
            result.success("查询成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    @Override
    public Result<?> saveRoleLayer(RoleDto roleDto) {
        long start = System.currentTimeMillis();
        Result<String> result = new Result<>();
        try {
            String roleId = roleDto.getRoleId();
            String permissionIds = roleDto.getPermissionIds();
            String lastPermissionIds = roleDto.getLastpermissionIds();
            this.vmRoleLayerService.saveRoleLayer(roleId, permissionIds, lastPermissionIds);
            LoginModel loginUser = (LoginModel) SecurityUtils.getSubject().getPrincipal();
            result.success("操作成功！");
            log.info("======角色授权成功=====耗时:{}毫秒", System.currentTimeMillis() - start);
        } catch (Exception e) {
            result.error500("授权失败！");
            log.error(e.getMessage(), e);
        }
        return result;
    }

    @Override
    public Result<List<String>> queryMenuLayer(String menuId) {
        Result<List<String>> result = new Result<>();
        try {
            List<VmPermissionLayer> list = vmPermissionLayerService.list(new QueryWrapper<VmPermissionLayer>().lambda().eq(VmPermissionLayer::getMenuId, menuId));
            result.setResult(list.stream().map(e -> String.valueOf(e.getLayerId())).collect(Collectors.toList()));
            result.success("查询成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    @Override
    public Result<?> saveMenuLayer(MenuLayerDto menuLayerDto) {
        long start = System.currentTimeMillis();
        Result<String> result = new Result<>();
        try {
            String menuId = menuLayerDto.getMenuId();
            String layerIds = menuLayerDto.getLayerIds();
            String lastLayerIds = menuLayerDto.getLastLayerIds();
            this.vmPermissionLayerService.savePermissionLayers(menuId, layerIds, lastLayerIds);
            LoginModel loginUser = (LoginModel) SecurityUtils.getSubject().getPrincipal();
            result.success("操作成功！");
            log.info("======菜单图层绑定成功=====耗时:{}毫秒", System.currentTimeMillis() - start);
        } catch (Exception e) {
            result.error500("授权失败！");
            log.error(e.getMessage(), e);
        }
        return result;
    }

    @Override
    public Result<?> batchAddElement(BatchAddElementDto batchAddElementDto) throws ClassNotFoundException {

        if (StringUtils.isEmpty(batchAddElementDto.getElementType()) || StringUtils.isEmpty(batchAddElementDto.getElementIds())) {
            return Result.error("参数不完整！");
        }
        //查询数据字典
        SysDictItem sysDictItem = sysDictItemService.lambdaQuery().eq(SysDictItem::getItemValue, batchAddElementDto.getElementType()).one();
        if (sysDictItem == null || StringUtils.isBlank(sysDictItem.getExtendService())) {
            return Result.error("数据字典配置不完整！");
        }
        VmLayer vmLayer = this.getById(batchAddElementDto.getLayerId());
        if (vmLayer == null) {
            return Result.error("图层不存在，请刷新重试！");
        }
        List<Object> lists = (List<Object>) vmCommonService.getListByMethod(
                new QueryElementDto(
                        batchAddElementDto.getLayerId(),
                        batchAddElementDto.getElementType(), "", "", "", "",
                        Arrays.asList(batchAddElementDto.getElementIds().split(","))
                ),
                sysDictItem.getExtendService(),
                BizConstant.COMMON_ELEMENT_LIST_METHOD
        );
        if (lists == null || lists.isEmpty()) {
            return Result.error("未找到图元数据！");
        }
        for (Object obj : lists) {
            JSONObject row = JSON.parseObject(JSON.toJSONString(obj));
            VmLayerElement vmLayerElement = vmLayerElementService.lambdaQuery()
                    .eq(VmLayerElement::getLayerId, vmLayer.getId())
                    .eq(VmLayerElement::getElementId, row.getString("id"))
                    .one();
            if (vmLayerElement == null) {
                vmLayerElement = new VmLayerElement(
                        vmLayer.getId(),
                        row.getString("id"),
                        row.getString(AnnotationUtil.getShowField(Class.forName(sysDictItem.getExtendEntity()), BizConstant.LABEL_ANNOTATION_TYPE_CODE)),
                        row.getString(AnnotationUtil.getShowField(Class.forName(sysDictItem.getExtendEntity()), BizConstant.LABEL_ANNOTATION_TYPE_NAME)),
                        row.getString(AnnotationUtil.getShowField(Class.forName(sysDictItem.getExtendEntity()), BizConstant.LABEL_ANNOTATION_TYPE_SCENE_LAYER_ID)),
                        batchAddElementDto.getElementType()
                );
                vmLayerElementService.save(vmLayerElement);
            }
        }
        return Result.ok("操作成功！");
    }

    @Override
    public Result<?> batchDeleteElement(BatchDeleteElementDto batchDeleteElementDto) {
        if (StringUtils.isEmpty(batchDeleteElementDto.getLayerId())) {
            return Result.error("参数不完整！");
        }
        if (StringUtils.isBlank(batchDeleteElementDto.getElementIds())) {
            return Result.error("参数不完整！");
        }
        List<String> ids = vmLayerElementService.lambdaQuery()
                .eq(VmLayerElement::getLayerId, batchDeleteElementDto.getLayerId())
                .in(VmLayerElement::getElementId, Arrays.asList(batchDeleteElementDto.getElementIds().split(",")))
                .list().stream().map(VmLayerElement::getId).collect(Collectors.toList());
        this.vmLayerElementService.removeByIds(ids);
        return Result.ok("操作成功！");
    }

    @Override
    public List<String> getElementIdsByType(String elementType) {
        return lambdaQuery().eq(VmLayer::getLayerType, elementType).list().stream().map(VmLayer::getId).collect(Collectors.toList());
    }

    @Override
    public Result<?> elementListByLayerId(ElementByLayerDto elementByLayerDto) {
        if (StringUtils.isEmpty(elementByLayerDto.getLayerId())) {
            return Result.error("参数不完整！");
        }
        LambdaQueryWrapper<VmLayerElement> queryWrapper = new LambdaQueryWrapper<>();
        if (Objects.equals(elementByLayerDto.getIsSub(), BizConstant.COMMON_YES_OR_NO_1)) {
            //递归查询所有的layerId
            List<VmLayer> layers = new ArrayList<>();
            getAllIdByParentId(layers, elementByLayerDto.getLayerId());
            List<String> ids = layers.stream().map(VmLayer::getId).collect(Collectors.toList());
            ids.add(elementByLayerDto.getLayerId());
            queryWrapper.in(VmLayerElement::getLayerId, ids);
        } else {
            queryWrapper.eq(VmLayerElement::getLayerId, elementByLayerDto.getLayerId());
        }
        queryWrapper.and(StringUtils.isNotBlank(elementByLayerDto.getKeywords()), wrapper -> wrapper
                .like(VmLayerElement::getElementCode, elementByLayerDto.getKeywords())
                .or()
                .like(VmLayerElement::getElementName, elementByLayerDto.getKeywords())
        );
        queryWrapper.eq(
                StringUtils.isNotBlank(elementByLayerDto.getElementType()),
                VmLayerElement::getElementType, elementByLayerDto.getElementType()
        );
        Page<VmLayerElement> page = new Page<>(elementByLayerDto.getPageNo(), elementByLayerDto.getPageSize());
        IPage<VmLayerElement> pageList = this.vmLayerElementService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    private void getAllIdByParentId(List<VmLayer> layers, String parentId) {
        List<VmLayer> nodes = this.lambdaQuery().in(VmLayer::getParentId, parentId).orderByAsc(VmLayer::getSort).list();
        if (!nodes.isEmpty()) {
            layers.addAll(nodes);
            for (VmLayer e : nodes) {
                this.getAllIdByParentId(layers, e.getId());
            }
        }
    }

    @Override
    public List<String> getAllSubIdsByParentId(String parentId) {
        if (StringUtils.isBlank(parentId)) {
            return Collections.emptyList();
        }
        List<String> ids = new ArrayList<>();
        ids.add(parentId);
        List<VmLayer> nodes = new ArrayList<>();
        this.getAllIdByParentId(nodes, parentId);
        if (!nodes.isEmpty()) {
            ids.addAll(nodes.stream().map(VmLayer::getId).collect(Collectors.toList()));
        }
        return ids;
    }

    @Override
    @Transactional
    public Result<?> copyLayer(String sourceLayerId, String targetParentId) {
        if (StringUtils.isBlank(sourceLayerId)) {
            return Result.error("参数不完整！");
        }
        VmLayer sourceLayer = this.getById(sourceLayerId);
        VmLayer oldLayer = BeanUtil.toBean(sourceLayer, VmLayer.class);
        if (sourceLayer == null) {
            return Result.error("图层不存在，请刷新重试！");
        }
        String newId = copyNode(sourceLayer, targetParentId);
        copyNodeByParent(oldLayer, newId);
        return Result.OK("操作成功！");
    }

    //复制节点
    private void copyNodeByParent(VmLayer sourceParent, String newParentId) {
        if (StringUtils.isEmpty(newParentId)) return;
        List<VmLayer> nodes = getAllSubNodeByParent(sourceParent);
        if (nodes.isEmpty()) return;
        for (VmLayer node : nodes) {
            VmLayer oldNode = BeanUtil.toBean(node, VmLayer.class);
            String newId = copyNode(node, newParentId);
            copyNodeByParent(oldNode, newId);
        }
    }

    //复制节点
    private String copyNode(VmLayer node, String targetParentId) {
        String sourceLayerId = node.getId();
        //复制根节点
        String uuId = UUID.randomUUID().toString();
        String parentId = StringUtils.isNotBlank(targetParentId) ? targetParentId : null;
        node.setId(uuId);
        node.setParentId(parentId);
        if (this.save(node)) {
            //复制action
            vmLayerActionService.copyActionByLayerId(sourceLayerId, uuId);
            //复制element
            vmLayerElementService.copyElementActionByLayerId(sourceLayerId, uuId);
            return uuId;
        }
        return "";
    }

    //查询所有子节点列表
    private List<VmLayer> getAllSubNodeByParent(VmLayer parent) {
        List<VmLayer> nodes = new ArrayList<>();
        List<VmLayer> subs = lambdaQuery().eq(VmLayer::getParentId, parent.getId()).list();
        if (subs == null || subs.isEmpty()) {
            return nodes;
        }
        //            nodes.addAll(getAllSubNodeByParent(sub));
        nodes.addAll(subs);
        return nodes;
    }

    @Override
    public Result<?> bindSceneLayer(String layerId, String sceneLayerId) {
        if (StringUtils.isEmpty(layerId)) {
            return Result.error("参数不完整！");
        }
        VmLayer vmLayer = this.getById(layerId);
        if (vmLayer == null) {
            return Result.error("数据不存在，请刷新重试！");
        }
        vmLayer.setSceneLayerId(sceneLayerId);
        if (this.updateById(vmLayer)) {
            return Result.ok("操作成功！");
        } else {
            return Result.error("操作失败！");
        }
    }

    @Override
    public Result<?> bindPointLayer(String layerId, String pointLayerId) {
        VmLayer vmLayer = this.getById(layerId);
        if (vmLayer == null) {
            return Result.error("数据不存在，请刷新重试！");
        }
        vmLayer.setPointLayerId(pointLayerId);
        if (this.updateById(vmLayer)) {
            return Result.ok("操作成功！");
        } else {
            return Result.error("操作失败！");
        }
    }

    @Override
    public Result<?> bindElementSceneLayer(String elementSId, String sceneLayerId) throws ClassNotFoundException {
        if (StringUtils.isEmpty(elementSId)) {
            return Result.error("参数不完整！");
        }
        VmLayerElement vmLayerElement = this.vmLayerElementService.getById(elementSId);
        if (vmLayerElement == null) {
            return Result.error("数据不存在，请刷新重试！");
        }
//        SysDictItem sysDictItem = sysDictItemService.lambdaQuery().eq(SysDictItem::getItemValue, vmLayerElement.getElementType()).one();
//        if (sysDictItem == null || StringUtils.isBlank(sysDictItem.getExtendService())) {
//            return Result.error("未找到【"+vmLayerElement.getElementType()+"】类型！");
//        }

        boolean res = false;
        if (StringUtils.equals(BizConstant.SCENE_ELEMENT_TYPE_MONITOR, vmLayerElement.getElementType())) {
            VmMonitor vmMonitor = Db.getById(vmLayerElement.getElementId(), VmMonitor.class);
            vmMonitor.setSceneLayerId(sceneLayerId);
            res = Db.save(vmMonitor);
        }
        if (StringUtils.equals(BizConstant.SCENE_ELEMENT_TYPE_ASSET, vmLayerElement.getElementType())) {
            VmAssets vmAssets = Db.getById(vmLayerElement.getElementId(), VmAssets.class);
            vmAssets.setSceneLayerId(sceneLayerId);
            res = Db.save(vmAssets);
        }
        if (res) {
            return Result.ok("操作成功！");
        } else {
            return Result.error("操作失败！");
        }
    }

    @Override
    public Result<?> getCountByLayerId(CountElementQuery countElementQuery) {
        if (StringUtils.isEmpty(countElementQuery.getLayerId())) {
            return Result.error("参数必填！");
        }
        List<VmLayer> nodes = new ArrayList<>();
        this.getAllIdByParentId(nodes, countElementQuery.getLayerId());
        List<String> ids = nodes.stream().map(VmLayer::getId).collect(Collectors.toList());
        ids.add(countElementQuery.getLayerId());

        return Result.ok(vmLayerElementService.lambdaQuery()
                .in(VmLayerElement::getLayerId, ids)
                .eq(StringUtils.isNotBlank(countElementQuery.getElementType()), VmLayerElement::getElementType, countElementQuery.getElementType())
                .count());
    }

    private void deleteLayer(String id) {
        VmLayer vmLayer = this.getById(id);
        if (vmLayer == null) {
            throw new MineBootException("未找到菜单信息");
        }
        this.removeById(id);
        vmLayerElementService.remove(new LambdaQueryWrapper<>(VmLayerElement.class).eq(VmLayerElement::getLayerId, id));
        // 该节点可能是子节点但也可能是其它节点的父节点,所以需要级联删除
        this.removeChildrenBy(id);
    }

    public void removeChildrenBy(String parentId) {
        LambdaQueryWrapper<VmLayer> query = new LambdaQueryWrapper<>();
        // 封装查询条件parentId为主键,
        query.eq(VmLayer::getParentId, parentId);
        // 查出该主键下的所有子级
        List<VmLayer> layerList = this.list(query);
        if (layerList != null && !layerList.isEmpty()) {
            String id = "";
            // 查出的子级数量
            long num = 0;
            // 如果查出的集合不为空, 则先删除所有
            this.remove(query);
            // 再遍历刚才查出的集合, 根据每个对象,查找其是否仍有子级
            for (VmLayer vmLayer : layerList) {
                id = vmLayer.getId();
                //删除角色授权表
                vmRoleLayerService.remove(new LambdaQueryWrapper<VmRoleLayer>().eq(VmRoleLayer::getLayerId, id));
                //删除菜单图层表
                vmPermissionLayerService.remove(new LambdaQueryWrapper<VmPermissionLayer>().eq(VmPermissionLayer::getLayerId, id));
                //删除图元表
                vmLayerElementService.remove(new LambdaQueryWrapper<>(VmLayerElement.class).eq(VmLayerElement::getLayerId, id));
                num = this.count(new LambdaQueryWrapper<VmLayer>().eq(VmLayer::getParentId, id));
                if (num > 0) {
                    this.removeChildrenBy(id);
                }
            }
        }
    }


}
